//
//  MainViewController.m
//  TMSTech
//
//  Created by cts on 2018/3/6.
//  Copyright © 2018年 hhjiang. All rights reserved.
//

#import "MainViewController.h"
#import <WebKit/WebKit.h>
#import "Header.h"
#import "AppDelegate.h"
@interface MainViewController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property(nonatomic,strong) WKWebView *wkWebview;
@property (nonatomic, strong) UIProgressView *progressView;

@end

@implementation MainViewController

//JS调用OC
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    if ([message.name isEqualToString:@"webViewApp"]) {
        NSDictionary *dict = message.body;
        //TODO
        
        if ([dict[@"type"] isEqualToString:@"createReport"] ) {
            NSLog(@"message.body = %@",message.body);
            
        }else if ([dict[@"type"] isEqualToString:@"backClick"]){
            
        }else if ([dict[@"type"] isEqualToString:@"findAccounting"]){
           
        }else if ([dict[@"type"] isEqualToString:@"accounMessage"]){
           
        }else if ([dict[@"type"] isEqualToString:@"quitLogin"]){
            
        }else if ([dict[@"type"] isEqualToString:@"clearCache"]){
            
        }
        
    }
}

- (void)dealloc {
    
    [[self.wkWebview configuration].userContentController removeScriptMessageHandlerForName:@"webViewApp"];
    
    [self.wkWebview removeObserver:self forKeyPath:@"estimatedProgress"];
}
#pragma mark - WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    //开始加载网页时展示出progressView
    self.progressView.hidden = NO;
    //开始加载网页的时候将progressView的Height恢复为1.5倍
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.2f);
    
    [self.view bringSubviewToFront:self.progressView];
    
    
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
    NSLog(@"加载完成");
    self.progressView.hidden = YES;
    
}
#pragma mark KVO的监听代理
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    
    
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        
        self.progressView.progress = self.wkWebview.estimatedProgress;
        
        if (self.progressView.progress == 1) {
            /*
             *添加一个简单的动画，将progressView的Height变为1.2倍，在开始加载网页的代理中会恢复为1.5倍
             *动画时长0.25s，延时0.3s后开始动画
             *动画结束后将progressView隐藏
             */
            __weak typeof (self)weakSelf = self;
            [UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                weakSelf.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.2f);
            } completion:^(BOOL finished) {
                weakSelf.progressView.hidden = YES;
                
            }];
        }
    }
    
    
    
    
}

-(void)createWebview{
    
    //初始化一个WKWebViewConfiguration对象
    WKWebViewConfiguration *config = [WKWebViewConfiguration new];
    //初始化偏好设置属性：preferences
    config.preferences = [WKPreferences new];
    //The minimum font size in points default is 0;
    config.preferences.minimumFontSize = 10;
    //是否支持JavaScript
    config.preferences.javaScriptEnabled = YES;
    WKUserContentController* userContent = [[WKUserContentController alloc] init];
    [userContent addScriptMessageHandler:self name:@"webViewApp"];
    
    config.userContentController = userContent;
    
    
    
    self.wkWebview = [[WKWebView alloc]initWithFrame:CGRectMake(0,20, kScreenWidth, kScreenHeight-20) configuration:config];
    self.wkWebview.UIDelegate = self;
    self.wkWebview.navigationDelegate = self;
    [self.view addSubview:self.wkWebview];
    
    [self.wkWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?sid=%@",KMain,Ksid]]]];
    //关闭自适应
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    [self.wkWebview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    //进度条初始化
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 20, [[UIScreen mainScreen] bounds].size.width, 2)];
    self.progressView.backgroundColor = [UIColor blueColor];
    //设置进度条的高度，下面这句代码表示进度条的宽度变为原来的1倍，高度变为原来的1.5倍.
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.2f);
    [self.view addSubview:self.progressView];
    [self createWebview];
    
    
}
//清理缓存
-(void)clearCache{
    NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
   
    
    NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
  
    
    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
        
        // Done
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.label.text = @"清理缓存成功";
        [hud hideAnimated:YES afterDelay:0.5f];
        
    }];
   
}
//退出登录
-(void)quitLogin{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"sid"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    AppDelegate *app = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [app setloginViewControlle];
}



@end
